package GUILayer;

import java.awt.*;
import java.util.ArrayList;

import java.awt.FlowLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;

import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;

import ControlLayer.SupplierCtr;
import ModelLayer.Supplier;
import javax.swing.GroupLayout.Alignment;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class SupplierGUI extends JPanel {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private SupplierCtr supplierCtr;
	private DefaultTableModel supplierTableModel;
	private JScrollPane supplierTableScrollPane;
	private JPanel showAllSupplierPanel;
	private JTable showAllSupplierTable;
	private JPanel supplierInfoPanel;
	private JPanel choicePanel;

	private JTextField textField_supplierId;
	private JTextField txt_Search;
	private JTextField textField_name;
	private JTextField textField_address;
	private JTextField textField_country;
	private JTextField textField_phone;
	private JTextField textField_email;

	private JButton btnSave;
	private JButton btnCreate;
	private JButton btnEdit;
	private JButton btnCancel;
	private JButton btnDelete;
	

	public SupplierGUI() {
		supplierCtr = new SupplierCtr();
		initialize();
	}
	//todo
	public void initialize() {
		this.setLayout(new BorderLayout());

		showAllSupplierPanel = new JPanel();
		this.add(showAllSupplierPanel, BorderLayout.CENTER);
		showAllSupplierPanel.setBorder(BorderFactory
				.createTitledBorder("Suppliers Info"));
		showAllSupplierPanel.setLayout(new BorderLayout());

		txt_Search = new JTextField();
		txt_Search.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent e) {
				showAllSuppliers();
			}
		});
		txt_Search.setColumns(10);

		JPanel searchPanel = new JPanel();
		showAllSupplierPanel.add(searchPanel, BorderLayout.NORTH);
		GroupLayout gl_searchPanel = new GroupLayout(searchPanel);
		gl_searchPanel.setHorizontalGroup(
			gl_searchPanel.createParallelGroup(Alignment.LEADING)
				.addComponent(txt_Search)
		);
		gl_searchPanel.setVerticalGroup(
			gl_searchPanel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_searchPanel.createSequentialGroup()
					.addGap(5)
					.addComponent(txt_Search, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
		);
		searchPanel.setLayout(gl_searchPanel);

		// show supplier info view
		JPanel showSupplierPanel = new JPanel();
		this.add(showSupplierPanel, BorderLayout.EAST);
		showSupplierPanel.setLayout(new BorderLayout());
		showSupplierPanel.setBorder(BorderFactory
				.createTitledBorder("Supplier"));

		supplierInfoPanel = new JPanel();
		JLabel lblsupplierId = new JLabel("Supplier Id: ");
		JLabel lblname = new JLabel("Name: ");
		JLabel lbladdress = new JLabel("Address: ");
		JLabel lblcountry = new JLabel("Country: ");
		JLabel lblphone = new JLabel("Phone: ");
		JLabel lblemail = new JLabel("E-mail: ");
		textField_supplierId = new JTextField();
		textField_supplierId.setEditable(false); // Id is not able changed
		textField_name = new JTextField();
		textField_address = new JTextField();
		textField_country = new JTextField();
		textField_phone = new JTextField();
		textField_email = new JTextField();
		
		GroupLayout gl = new GroupLayout(supplierInfoPanel);
		supplierInfoPanel.setLayout(gl);
		supplierInfoPanel.setBorder(BorderFactory.createTitledBorder("Info"));
		gl.setAutoCreateGaps(true);
		gl.setAutoCreateContainerGaps(true);

		gl.setHorizontalGroup(gl
				.createSequentialGroup()
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.LEADING)
								.addComponent(lblsupplierId)
								.addComponent(lblname).addComponent(lbladdress)
								.addComponent(lblcountry).addComponent(lblphone)
								.addComponent(lblemail))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.LEADING)
								.addComponent(textField_supplierId)
								.addComponent(textField_name)
								.addComponent(textField_address)
								.addComponent(textField_country)
								.addComponent(textField_phone)
								.addComponent(textField_email)));
		gl.setVerticalGroup(gl
				.createSequentialGroup()
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblsupplierId)
								.addComponent(textField_supplierId))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblname)
								.addComponent(textField_name))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lbladdress)
								.addComponent(textField_address))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblcountry)
								.addComponent(textField_country))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblphone)
								.addComponent(textField_phone))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblemail)
								.addComponent(textField_email)));

		showSupplierPanel.add(supplierInfoPanel, BorderLayout.NORTH);

		choicePanel = new JPanel();
		choicePanel.setLayout(new FlowLayout());
		btnCreate = new JButton("Create/New");
		btnEdit = new JButton("Edit");
		btnEdit.setEnabled(false);
		btnSave = new JButton("Save");
		btnEdit.setEnabled(false);
		btnCancel = new JButton("Cancel/Clear");
		btnDelete = new JButton("Delete");
		
		choicePanel.add(btnCreate);
		choicePanel.add(btnEdit);
		choicePanel.add(btnDelete);
		choicePanel.add(btnSave);
		choicePanel.add(btnCancel);
		showSupplierPanel.add(choicePanel, BorderLayout.CENTER);
		
		addSuppliersTable();
		showAllSuppliers();

		btnCreate.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				supplierCtr.insertSupplier(textField_name.getText(),
						textField_address.getText(), textField_country.getText(),
						Integer.parseInt(textField_phone.getText()),
						textField_email.getText());
				cleanTextField();
				showAllSuppliers();
			}
		});
		
		btnDelete.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int reply = JOptionPane.showConfirmDialog(null,
						"Do you want to delete this supplier?",
						"Delete Supplier", JOptionPane.YES_NO_OPTION,
						JOptionPane.WARNING_MESSAGE);
				if (reply == JOptionPane.YES_OPTION) {
					try {
						supplierCtr.deleteSupplier(Integer
								.parseInt(textField_supplierId.getText()));
						cleanTextField();
						showAllSuppliers();
					} catch (Exception e1) {
					}
				}
			}
		});

		btnEdit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				isTextFieldEditable(true);
				btnSave.setEnabled(true);
				btnDelete.setEnabled(true);
				btnCreate.setEnabled(false);
			}
		});
		
		btnSave.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
				supplierCtr.updateSupplier(
						Integer.parseInt(textField_supplierId.getText()), 
						textField_name.getText(),
						textField_address.getText(), 
						textField_country.getText(), 
						Integer.parseInt(textField_phone.getText()),
						textField_email.getText());
				} catch (Exception a) {
					JOptionPane.showMessageDialog(null, "Please input correct values", "Error",
							JOptionPane.ERROR_MESSAGE);
				}
				btnEdit.setEnabled(false);
				btnSave.setEnabled(false);
				btnCreate.setEnabled(true);
				showAllSuppliers();
			}
		});
		
		btnCancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				cleanTextField();
				btnSave.setEnabled(false);
				btnEdit.setEnabled(false);
				btnCreate.setEnabled(true);
			}
		});

	}

	public void addSuppliersTable() {
		supplierTableModel = new DefaultTableModel() {
			private static final long serialVersionUID = 1L;

			@Override
			public boolean isCellEditable(int row, int column) {
				return false;
			}
		};
		supplierTableModel.addColumn("ID");
		supplierTableModel.addColumn("Supplier");
		supplierTableModel.addColumn("Address");
		supplierTableModel.addColumn("Country");
		supplierTableModel.addColumn("Phone");
		supplierTableModel.addColumn("E-mail");

		supplierTableScrollPane = new JScrollPane();

		showAllSupplierPanel.add(supplierTableScrollPane, BorderLayout.CENTER);

		showAllSupplierTable = new JTable(supplierTableModel);
		showAllSupplierTable.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN);
		showAllSupplierTable.setAutoCreateRowSorter(true);

		showAllSupplierTable.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				btnCreate.setEnabled(false);
				btnEdit.setEnabled(true);
				int row = showAllSupplierTable.rowAtPoint(e.getPoint());
				if (e.getClickCount() == 2) {
					if (showSupplier(Integer
							.valueOf((Integer) showAllSupplierTable.getValueAt(
									row, 0)))) {
					}
				}
			}
		});
		supplierTableScrollPane.setViewportView(showAllSupplierTable);
	}

	public void showAllSuppliers() {
		
		String searchFilter = txt_Search.getText();
		
		ArrayList<Supplier> suppliers = supplierCtr.getAllSuppliers();
		supplierTableModel.setRowCount(0);
		for (Supplier supplier : suppliers) {
			if (((Integer) supplier.getId()).toString().toLowerCase()
					.contains(searchFilter.toLowerCase())
					|| supplier.getName().toLowerCase()
							.contains(searchFilter.toLowerCase())  || supplier.getEmail().toLowerCase().contains(searchFilter.toLowerCase()))
			try {
				supplierTableModel.addRow(new Object[] { supplier.getId(),
						supplier.getName(), supplier.getAddress(),
						supplier.getCountry(), supplier.getPhone(),
						supplier.getEmail() });
			} catch (Exception e) {
				JOptionPane.showMessageDialog(null, e, "Error",
						JOptionPane.ERROR_MESSAGE);
			}
		}

	}

	public boolean showSupplier(int supplierId) {
		boolean success = true;
		Supplier supplier = null;
		try {
			if (supplierId != 0) {
				supplier = supplierCtr.getSupplier(supplierId);
			}
		} catch (Exception e) {
			success = false;
			JOptionPane.showMessageDialog(null, e, "Error",
					JOptionPane.ERROR_MESSAGE);
			return success;
		}

		if (success) {
			textField_supplierId.setText(Integer.toString(supplier.getId()));
			textField_name.setText(supplier.getName());
			textField_address.setText(supplier.getAddress());
			textField_country.setText(supplier.getCountry());
			textField_phone.setText(Long.toString(supplier.getPhone()));
			textField_email.setText(supplier.getEmail());
			isTextFieldEditable(false);
		}
		return success;
	}
	
	public void refreshTable() {
		
	}

	public void isTextFieldEditable(boolean isEditable) {
		textField_name.setEditable(isEditable);
		textField_address.setEditable(isEditable);
		textField_country.setEditable(isEditable);
		textField_phone.setEditable(isEditable);
		textField_email.setEditable(isEditable);
	}

	public int getTextFieldId(JTextField textField) {
		int id = 0;
		try {
			id = Integer.parseInt(textField.getText());
		} catch (NumberFormatException e) {
			JOptionPane.showMessageDialog(null, "Please input number", "Error",
					JOptionPane.ERROR_MESSAGE);
		} finally {
			textField.setText("");
		}
		return id;
	}

	public void cleanTextField() {
		txt_Search.setText("");
		textField_supplierId.setText("");
		textField_name.setText("");
		textField_address.setText("");
		textField_country.setText("");
		textField_phone.setText("");
		textField_email.setText("");
	}

}
